package ua.kharkov.khpi.tarasenko.bach.web.command.user;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.order.OrderStatus;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.order.OrderUserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to pay for order.
 * 
 * @author oleksandr
 * 
 */
public class PayForOrderCommand extends Command {
	private static final Logger log = Logger
			.getLogger(PayForOrderCommand.class);

	private static final String ATTRIBUTE_IS_SUCCESSFULY_PAID = "isSuccessfulyPaid";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		// Get user's id from session
		HttpSession session = request.getSession();
		int userId = ((UserBean) session
				.getAttribute(Constant.ATTRIBUTE_USER_BEAN)).getUserId();
		if (log.isTraceEnabled()) {
			log.trace("User id from user bean is " + userId);
		}

		// Get order's id from request
		String orderIdString = request
				.getParameter(Constant.ATTRIBUTE_ORDER_ID);
		if (log.isTraceEnabled()) {
			log.trace("Got parameter from request "
					+ Constant.ATTRIBUTE_ORDER_ID + "=" + orderIdString);
		}

		boolean isSuccessfulyPaid = false;
		String errorMessage = null;
		String forward = Constant.PAGE_PAY_FOR_ORDER_RESULT;
		Connection conn = null;

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		// If order id is null or empty than we throw an exception.
		if ((orderIdString == null) || orderIdString.isEmpty()) {
			errorMessage = LRManager
					.getMessage("error_message.order_id_not_spec");
		} else {

			int orderId = Integer.valueOf(orderIdString);
			try {

				// Create OrderUserDTO to update general order's info
				OrderUserDTO orderUserDTO = new OrderUserDTO();
				orderUserDTO.setOrderId(orderId);
				orderUserDTO.setUserId(userId);

				// Now item is bought, so assign it status PAYED
				orderUserDTO.setStatus(OrderStatus.PAID);

				// Now we are ready to update order status
				conn = ConnectionManager.getConnection();
				int rowsUpdated = DAOFactory
						.getDAOFactory(DAOFactory.DAO_TYPE.MYSQL)
						.getOrderUserDAO(conn)
						.updateOrderUserStatus(orderUserDTO);

				// If we have one updated row - everything is ok.
				if (rowsUpdated == 1) {
					isSuccessfulyPaid = true;
					log.info("User with uid=" + userId
							+ " payed for order with oid=" + orderId);
				}

				// Put list of orders into request.
				request.setAttribute(ATTRIBUTE_IS_SUCCESSFULY_PAID,
						isSuccessfulyPaid);
				if (log.isTraceEnabled()) {
					log.trace("Set request attribute "
							+ ATTRIBUTE_IS_SUCCESSFULY_PAID + "="
							+ isSuccessfulyPaid);
				}
				DBUtils.commitAndClose(conn);
			} catch (EShopException e) {
				DBUtils.rollBackAndClose(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}
}